// 公共逻辑
import { useEffect, useState } from 'react';
import { message } from 'antd';

/**
 * 获取详情数据
 * @param getData   Promise，返回对象
 * @param initState 初始化状态值
 */
export const useDetail = ({ getData, initState = {
    currentProcessTaskInstance: {},
    relatedBusinessObject: {},
    processTaskInstances: [],
    processTaskTemplates: []
} }) => {
    const [loading, setLoading] = useState(false);
    const [detail, setDetail] = useState(initState);

    useEffect(() => {
        const fetchData = async () => {
            if (getData) {
                if (typeof getData !== 'function') throw new Error('getData 必须是一个返回 Promise 的函数！');
                setLoading(true);
                try {
                    setDetail(await getData());
                } catch (e) {
                    message.error(e.message);
                }
                setLoading(false);
            } else {
                throw new Error('请传递 getData 函数！');
            }
        };

        fetchData();
    }, [getData]);

    return {
        loading,
        detail
    }
};
